import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // 请求拦截携带token
    if (store.getters.token) {
      // 判断token是否过期
      if ((Date.now() - store.getters.tokenTime) >= 1000 * 60 * 60) {
        store.dispatch('user/logout')
        return
      } else {
      // 加请求头
        config.headers['Authorization'] = `Bearer ${store.getters.token}`
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    const data = response.data
    if (data.success) {
      // 成功正常返回剥离后的数据
      return data
    } else {
      // 失败就弹出错误消息
      Message.error({
        showClose: true,
        message: data.message
      })
      // 并抛出错误
      throw Error(data.message)
    }
  },
  error => {
    // token过期 - 被动处理
    if (error.response.status === 401) {
      store.dispatch('user/logout')
    }
    console.dir(error.response.status)
    return Promise.reject(error)
  }
)

export default service
